package com.zqweb.gulimall.essearch.service.impl;

import com.alibaba.fastjson.JSON;
import com.zqweb.common.es.SkuESModel;
import com.zqweb.gulimall.essearch.config.ESClientConfig;
import com.zqweb.gulimall.essearch.service.EsSaveService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class EsSaveServiceImpl implements EsSaveService {
    @Autowired
    // 注入ES的RestHighLevelClient客户端操作对象
    private RestHighLevelClient restHighLevelClient;

    @Override
    // 保存商品ES模型数据
    public boolean saveESModel(List<SkuESModel> skuESModels) throws IOException {
        BulkRequest bulkRequest = new BulkRequest();
        for (SkuESModel skuESModel : skuESModels) {
            // 指定每个ESModel的存储index
            IndexRequest indexRequest = new IndexRequest("gulimall_product");
            // 指定每个ESModel存储时的id
            indexRequest.id(skuESModel.getSkuId().toString());
            // 指定存储时文档记录的source体
            indexRequest.source(JSON.toJSONString(skuESModel), XContentType.JSON);
            // 将配置好的indexRequest对象添加到bulkRequest上
            bulkRequest.add(indexRequest);
        }
        // 传入bulkRequest对象，执行批量bulk操作
        BulkResponse bulkResponse = restHighLevelClient.bulk(bulkRequest, ESClientConfig.COMMON_OPTIONS);
        // 根据bulkResponse对象，确定ES模型数据的保存结果
        boolean status = bulkResponse.hasFailures();
        List<String> idList = Arrays.stream(bulkResponse.getItems()).map(item -> item.getId()).collect(Collectors.toList());
        // status反映的是商品数据传给ES服务器后，作数据处理时发生了异常，而不是网络不通未将数据传给ES服务器
        log.info("商品{},上架正常！",idList);
        return status;
    }
}
